package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.MarketAddress;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.service.wx.WXAddressService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author :rain
 * @description
 * @since 2022/06/28 21:21
 */
@RestController
@RequestMapping("wx/address")
public class WXAddressController {

    @Autowired
    WXAddressService wxAddressService;

    /**
     * 获取所有的地址信息
     *
     * @return
     */
    @RequestMapping("list")
    public BaseRespVo list() {
        //获取当前用户的信息
        Subject subject = SecurityUtils.getSubject();
        //拿到当前用户
        PrincipalCollection principals = subject.getPrincipals();
        if (principals == null){
            return BaseRespVo.error(501,"需要重新登陆");
        }
        MarketUser currentUser = (MarketUser) principals.getPrimaryPrincipal();
        //MarketUser currentUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        CommonData<MarketAddress> data = wxAddressService.queryAdressInfo(currentUser);
        return BaseRespVo.ok(data);
    }

    /**
     * 根据用户的地址信息的id获取到用的地址信息
     *
     * @param id 用户的地址信息的id
     * @return
     */
    @RequestMapping("detail")
    public BaseRespVo detail(Integer id) {
        MarketAddress address = wxAddressService.queryByAddressId(id);
        return BaseRespVo.ok(address);
    }

    /**
     * 修改方法
     *
     * @param address 传过来的是地址的对象
     * @return 返回的是修改地址信息的id
     */
    @RequestMapping("save")
    public BaseRespVo save(@RequestBody MarketAddress address) {
        //登陆成功后，操作都是同一个subject
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        if (principals == null){
            return BaseRespVo.error(501,"需要重新登陆");
        }
        MarketUser currentUser = (MarketUser) principals.getPrimaryPrincipal();
        //MarketUser currentUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer id = wxAddressService.updateAddressInfo(address, currentUser);
        if (id == null) {
            return BaseRespVo.invalidData();
        }
        return BaseRespVo.ok(id);
    }

    /**
     * 根据当前地址信息的id删除地址信息(假删除)
     * @param address 将id封装到address中
     * @return
     */
    @RequestMapping("delete")
    public BaseRespVo delete(@RequestBody MarketAddress address) {
        Integer affactRows = wxAddressService.deleteById(address);
        if (affactRows == null) {
            return BaseRespVo.invalidData();
        }
        return BaseRespVo.ok();
    }
}
